<?php
namespace Modules\User\Http\Controllers\Client\V1;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

use Modules\User\Entities\User;

use Modules\Core\Helpers\HttpClient;

use Validator;
use ThrowException;
use Auth;
use DB;
use Cache;
use Miniapp;
use Wechat;
use Setting;
use SMS;

class H5Controller extends Controller
{
    // H5手机号登陆
    public function loginWithPhoneCode(Request $req)
    {
        $rule = [
            'phone' => ['required'],
            'phone_code' => ['required'],
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();

        // 手机号简单验证
        if ($req->input('phone')) {
            if (strlen($req->phone) !== 11) {
                ThrowException::Conflict('手机号格式不正确~');
            }
        }

        $phone = $req->phone;
        // 校验验证码是否正确
        if ($phone !== @Setting::get('sys_preset_account')['phone'] || $req->phone_code !== @Setting::get('sys_preset_account')['phone_code']) {
            SMS::verifyCode($req->phone, $req->phone_code, 'login') || ThrowException::Conflict('验证码不正确');
        }

        // 是否已绑定微信
        $isBindWechat = false;
        // 是否创建
        $isCreated = false;
        
        DB::beginTransaction();

        $user = User::where('phone', $phone)->first();

        if (!$user) {

            // 创建用户
            $user = User::createWithPhone($phone);

            $isCreated = true;
        }

        $openidType = Auth::platformType();
        // \Log::error('openid type ====>' . $openidType);
        if ($user->wechats()->where('openid_type', $openidType)->first()) {
            $isBindWechat = true;
        }

        // 绑定邀请人
        if ($req->input('inviter') && $isCreated) {
            $inviter = User::getEntity([
                'uuid' => $req->inviter
            ], false);

            $user->bindInviter($inviter);
        }

        DB::commit();

        $token = Auth::generateToken($user);

        return [
            'token' => $token,
            'is_first_login' => $isCreated ? 1 : 0,
            'is_bind_wechat' => $isBindWechat ? 1 : 0
        ];
    }

    // h5绑定微信
    public function bindWechat(Request $req)
    {
        $rule = [
            'code' => ['required'],
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();

        \Log::error('login with code: ' . $req->code);

        $user = Auth::requireLoginUser();

        $wechatInfo = Wechat::get()->getUser()->getOriginal();

        $openId = $wechatInfo['openid'];
        $unionId = @$wechatInfo['unionid'];

        // 绑定
        $where = [
            'openid' => $openId,
            'openid_type' => 'web',
            'client_name' => 'default',
        ];

        if (!$user->wechats()->where($where)->first()) {
            $user->wechats()->create([
                'uuid' => uniqid(),
                'openid' => $openId,
                'unionid' => $unionId,
                'headimgurl' => @$data['headimgurl'],
                'nickname' => @$data['nickname'],
                'openid_type' => 'web',
                'client_name' => 'default',
                'type' => 'wechat'
            ]);
        }

        return [
        ];
    }
}
